﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Entity;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.Kho.UTI;
using ThaiHoa.Win.QLSX.DAL;
using Excel = Microsoft.Office.Interop.Excel;

namespace ThaiHoa.Win.QLSX.Kho.UI
{
    public partial class frmLoaiMayMoc_old : Form
    {
           #region Fields
        KhoDBContext db;
        BindingSource loaiMayMocBS;
        private bool HasChanged = false;
        #endregion
        #region Contructor
        public frmLoaiMayMoc_old()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void BindData()
        {
            db = new KhoDBContext();
            loaiMayMocBS = new BindingSource();
            this.loaiMayMocBS.AddingNew += new AddingNewEventHandler(loaiMayMocBS_AddingNew);
            this.loaiMayMocBS.ListChanged += new ListChangedEventHandler(loaiMayMocBS_ListChanged);
            db.LoaiMayMoc.Where(t => t.TrangThai).Load();
            loaiMayMocBS.DataSource = db.LoaiMayMoc.Local.ToBindingList();
            //binding for navigator
            loaiMayMocBN.BindingSource = loaiMayMocBS;
            //binding for gridview
            dgvLoaiMayMoc.AutoGenerateColumns =true;
            dgvLoaiMayMoc.DataSource = loaiMayMocBS;
            CustomerGridView();
            //binding for textbox
            txtTenLoai.DataBindings.Add("Text", loaiMayMocBS, "TenLoai");
            txtMoTa.DataBindings.Add("Text", loaiMayMocBS, "MoTa");
            //binding for combobox
        }
        private void CustomerGridView()
        {
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvLoaiMayMoc.Columns)
            {
                item.Visible = false;
            }
            //Tùy chỉnh lại
            //Tên loại
            var c = dgvLoaiMayMoc.Columns["TenLoai"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 1;

            c = dgvLoaiMayMoc.Columns["Id"];
            c.Visible = true;

            //Mô tả
            c = dgvLoaiMayMoc.Columns["MoTa"];
            c.Visible = true;
            c.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            c.DisplayIndex = 2;

        }
        private void SaveChange()
        {
            if (HasChanged)
            {
                if (MessageBox.Show("Lưu thay đổi ?", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    db.SaveChanges();
                    HasChanged = false;
                }
            }          
        }

        /// <summary>
        /// Kiểm tra có trùng tên không
        /// Dung cho truong hop them moi
        /// True : Ko trùng
        /// False :Trùng
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <returns></returns>
        private bool KiemTraTrungTen(string tenLoai)
        {
            List<LoaiMayMoc> listLoaiMayMoc = db.LoaiMayMoc.Where(m=>m.TrangThai).ToList();
            if (listLoaiMayMoc.Any(l => l.TenLoai.Equals(tenLoai)))
                return false;
            return true;
        }
        /// <summary>
        /// Kiem tra co trung tên ko
        /// Dung cho truong hop edit
        /// 
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <param name="thepDac"></param>
        /// <returns></returns>
        private bool KiemTraTrungMa(string tenLoai, LoaiMayMoc loaiMayMoc)
        {
            List<LoaiMayMoc> listLoaiMayMoc = db.LoaiMayMoc.Where(m => m.TrangThai).ToList();
            if (listLoaiMayMoc.Any(l => l.TenLoai.Equals(tenLoai) && !l.Id.Equals(loaiMayMoc.Id)))
                return false;
            return true;
        }
        private void ExportToExcel()
        {
            string workbookPath=Application.StartupPath + @"\Template\Excel\JAT_LoaiMayMoc";
            Excel.Application xlApp=new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
            Excel.Worksheet xlWorkSheet=(Excel.Worksheet)xlWorkBook.Worksheets[1];
            xlWorkBook.Activate();
            xlWorkSheet.Name="LoaiMayMoc";
            //Add data
            var listLoaiMayMoc=loaiMayMocBS.List;
            int count=0;
            int positonStart = 11;
            string start;
            string stop;
            Excel.Range r;
            foreach (LoaiMayMoc item in listLoaiMayMoc)
            {
                xlWorkSheet.Cells[positonStart + count, 1] = count + 1;
                xlWorkSheet.Cells[positonStart + count, 2] = item.TenLoai;
                xlWorkSheet.Cells[positonStart + count, 3] = item.MoTa;


                //Format it               

                start = "A" + (count + positonStart).ToString();
                stop = "E" + (count + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start,stop);
                r.Borders.Color = Color.Black;
                r.RowHeight = 30;
                //r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                r.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                //merge
                start = "C" + (count + positonStart).ToString();
                stop = "E" + (count + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Merge();
                count++;

                
            }
            //định dạng cho phần header
            LoaiMayMoc loaiMayMoc = loaiMayMocBS.Current as LoaiMayMoc;
            if (loaiMayMoc != null)
            {
                r = (Excel.Range)xlWorkSheet.get_Range("A4", "D4");

                //Tùy biến tên phiên bản
                xlWorkSheet.Cells[6, 4] = "";
                xlWorkSheet.Cells[7, 4] = "Ngày " + loaiMayMoc.NgayTao.ToString("dd/MM/yyy");
            }
            // Ẩn chương trình
            xlApp.Visible = false;

            // Save file
            xlWorkBook.SaveAs("C:\\JAT_LoaiThietBi.xls", Excel.XlFileFormat.xlWorkbookNormal,
                            null, null, false, false,
                            Excel.XlSaveAsAccessMode.xlExclusive,
                            false, false, false, false, false);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);


            
            MessageBox.Show("File created !");
        }
        #endregion
        #region Events
        private void frmLoaiMayMoc_Load(object sender, EventArgs e)
        {
           
            BindData();
            HasChanged = false;
        }
        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            SaveChange();
        }
        private void dgvLoaiMayMoc_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Common.ShowMessengerError(e.Exception.Message);
        }

        private void dgvLoaiMayMoc_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            // Bắt lỗi cho cell tên loại

            if (dgvLoaiMayMoc.Columns[e.ColumnIndex].Name == "TenLoai")
            {
                if (this.dgvLoaiMayMoc.IsCurrentCellInEditMode)
                {
                    Guid oldId = (Guid)dgvLoaiMayMoc.Rows[e.RowIndex].Cells["Id"].Value;
                    string tenMoi = this.dgvLoaiMayMoc.EditingControl.Text;
                    if (oldId == null) return;
                    LoaiMayMoc oldLoaiMayMoc = db.LoaiMayMoc.FirstOrDefault(t =>t.TrangThai && t.Id.Equals(oldId));
                    if (oldLoaiMayMoc == null) return;
                    if (!KiemTraTrungMa(tenMoi, oldLoaiMayMoc))
                    {
                        Common.ShowMessengerError("Tên này đã được sử dụng");
                        this.dgvLoaiMayMoc.EditingControl.Text = oldLoaiMayMoc.TenLoai;
                        e.Cancel = true;
                    }
                }
            }

        }

        private void dgvLoaiMayMoc_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            
        }


        private void loaiMayMocBS_AddingNew(object sender, AddingNewEventArgs e)
        {
                        
        }
        private void loaiMayMocBS_ListChanged(object sender, ListChangedEventArgs e)
        {
            HasChanged = true;
        }
        private void printToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void exportToolTripButton_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        #endregion

        private void frmLoaiMayMoc_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveChange();
        }
    }
}
